package com.zprmb.udzt;

import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zprmb.udzt.gesture.GestureEditActivity;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.ll.BaseHelper;
import com.zprmb.udzt.rsa.Base64;
import com.zprmb.udzt.rsa.ConfigureEncryptAndDecrypt;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.VolleryUtil;
/**
 * 登录
 * @author shenshao
 *
 */
public class LoginActivity extends BaseLogActivity implements OnClickListener{
	private TextView tv_user_phone,message_login,forgetpwd,tv_switch;
	private EditText et_pwd;
	private Button btn_login;
	private TextView tv_customer;
	private String csrf;
	private String mobile;
	private int who=4;//0为默认   传1代表登录成功后直接finish登录界面   2代表从main里来  
	private ImageView img_back,pass;
	private RelativeLayout rl_back;
	private int message;
	private static final String publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCb9I0Uohf2nTP3zyOk7q+Fuo7szbp0XYFzW0ik52DGnLH6TGooO1DIjbgQ8GgsW6YH0xby/R4eWc1U4U64jSGKiIcYRmUQvSWuPiKk8qT9g6ukMcMmNg3nWH2KOWPyYADOPL3w1maVB6+SZ/G8c9pTqjQlpLmTFM9sFy09v2+RGQIDAQAB";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login2);
		 BbtApplication.getInstance().addActvity(this);
		tv_user_phone=(TextView)findViewById(R.id.login_user_phone);
		btn_login=(Button)findViewById(R.id.btn_login);
		et_pwd=(EditText)findViewById(R.id.login_pwd);
		pass=(ImageView)findViewById(R.id.img_pass);
		tv_customer=(TextView)findViewById(R.id.enterprise_tel);
		message_login=(TextView)findViewById(R.id.message_login);
		forgetpwd=(TextView)findViewById(R.id.forget_pwd);
		img_back=(ImageView)findViewById(R.id.img_back);
		tv_switch=(TextView)findViewById(R.id.switch_account);
		rl_back=(RelativeLayout)findViewById(R.id.rl_back);
		message=getIntent().getIntExtra("message", 0);
		rl_back.setOnClickListener(this);
		img_back.setOnClickListener(this);
		forgetpwd.setOnClickListener(this);
		tv_switch.setOnClickListener(this);
		message_login.setOnClickListener(this);
		pass.setOnClickListener(this);
		tv_customer.setOnClickListener(this);
		who=getIntent().getIntExtra("who", 4);
		
		btn_login.setOnClickListener(this);
		forgetpwd.setOnClickListener(this);
        et_pwd.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@SuppressLint("NewApi")
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(et_pwd.getText().toString().length()<6){
					btn_login.setBackgroundResource(R.drawable.btn_unclick);
					btn_login.setEnabled(false);
				}else{
					btn_login.setBackgroundResource(R.drawable.my_button);
					btn_login.setEnabled(true);
				}
				if(et_pwd.getText().toString().equals("")){
					pass.setVisibility(View.GONE);
				}else{
					pass.setVisibility(View.VISIBLE);
				}
			}
		});
	}
	public static PublicKey getPublicKey(String key) throws Exception {
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
				Base64.decodeBase64(key.getBytes()));
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}
	public  String encrypt(String source, String publicKey)
			throws Exception {
		Key key = getPublicKey(publicKey);
		/** 得到Cipher对象来实现对源数据的RSA加密 */
		Cipher cipher = Cipher.getInstance(ConfigureEncryptAndDecrypt.RSA_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] b = source.getBytes();
		/** 执行加密操作 */
		byte[] b1 = cipher.doFinal(b);
		return new String(Base64.encodeBase64(b1),
				ConfigureEncryptAndDecrypt.CHAR_ENCODING);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
        if(getShare().getString("mobile", "").equals("")){
			
			mobile=getIntent().getStringExtra("phone");
		}else{
			mobile=getShare().getString("mobile", "13000000000");
			
		}
		String maskNumber=mobile;
		tv_user_phone.setText(maskNumber);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		BbtApplication.getInstance().removeActvity(this);
	}
	private void initData() {
		// 这个接口返回的请求头里有3个参数，，前两个暂时写死！
		VolleryUtil vollery=new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				try {
					
					if (jsonObject.optInt("success") == 1) {
						csrf = jsonObject.getJSONObject("data").optString(
								"csrf");
						upData();
					} else {
						
						Toast.makeText(LoginActivity.this,
								jsonObject.optString("comment"), 0).show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		vollery.setHeaders("appId", "bbt3.0:android");
		vollery.setHeaders("appSecret", "RH89xcYh");
		vollery.setHeaders("appVersion", getAppVersion());
		vollery.setRequestMethod(1);
		
		vollery.execute(this, Constant.URL + "api/csrf", "");
	}
	private void upData() {
		AjaxParams params = new AjaxParams();
		params.put("loginName", mobile);
		params.put("password", et_pwd.getText().toString());
		params.put("appVersion", getAppVersion());
		VolleryUtil vollery = new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				Log.e("ssssg", jsonObject.toString());
					JSONObject json1=jsonObject.optJSONObject("data");
					if (jsonObject.optInt("success") == 1) {
						btn_login.setBackgroundResource(R.drawable.my_button);
						btn_login.setText("登录");
						btn_login.setEnabled(true);
						Editor editor = getShare().edit();
						editor.putString(
								"token",
								json1.optString(
										"token"));
						editor.putString(
								"userId",
								json1.optString(
										"userId"));
						editor.putString(
								"photoUrl",
								json1.optString(
										"photoUrl"));
						editor.putString(
								"mobile",
								json1.optString(
										"mobile"));
						editor.putString(
								"usercode",
								json1.optString(
										"userCode"));
						try {
							editor.putString(
									"password",
									encrypt(et_pwd.getText().toString().trim(), publicKey));
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						editor.putString("loginName", getIntent().getStringExtra("phone"));
						editor.commit();
						
						Toast.makeText(LoginActivity.this,jsonObject.optString("comment"), 0).show();
						if (getShare().getString(getMobile(), "").equals("")) {
							Intent intent = new Intent(LoginActivity.this,GestureEditActivity.class);//MainActivity
							intent.putExtra("towhere", "main");
							startActivity(intent);
							LoginActivity.this.finish();
							return;
						}
						if(message==1){
							Intent intent = new Intent(LoginActivity.this,V4WebViewActivity.class);
							//MainActivity
							intent.putExtra("url", "/h5/messageCenter?app=true&token="+json1.optString(
									"token"));
							intent.putExtra("title", "我的消息");
							Log.e("login_token", json1.optString(
									"token")); 
							startActivity(intent);							
							LoginActivity.this.finish();
							return;
						}
						if (who==4) {
							LoginActivity.this.finish();
							return;
						}
						if (who==3) {
							
							if(getIntent().getIntExtra("web", 0)==1){
								Intent intent=new Intent();
								intent.putExtra("resultcode", 1);
								setResult(1,intent);
								Log.e("web", "web");
								finish();
							}else{
								LoginActivity.this.finish();
							}
							return;
						}
//						Intent intent = new Intent(LoginActivity.this,MainActivity.class);AccountActivity
						//MainActivity
						Intent intent = new Intent(LoginActivity.this,MainActivity.class);
						startActivity(intent);
						
						LoginActivity.this.finish();
					} else {
						btn_login.setBackgroundResource(R.drawable.my_button);
						btn_login.setText("登录");
						btn_login.setEnabled(true);
						Toast.makeText(LoginActivity.this,jsonObject.optString("comment"), 0).show();
					}
				
			}

			@Override
			public void onError() {
				// TODO Auto-generated method stub
				btn_login.setBackgroundResource(R.drawable.my_button);
				btn_login.setText("登录");
				btn_login.setEnabled(true);
			}
		};
		vollery.setHeaders("csrf", csrf);
		vollery.setHeaders("client", "android");
		vollery.setHeaders("deviceToken", getdevice_token());
		vollery.setRequestMethod(1);
		vollery.setShow(true);
		vollery.execute(this, Constant.URL + "api/login?",
				params.toString());
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			 if(who==3){
				 LoginActivity.this.finish();
			}else if(who==5){
				
				LoginActivity.this.finish();
				
			}else{
				Intent intent5 = new Intent(LoginActivity.this,MainActivity.class);
				startActivity(intent5);
			}
			 return super.onKeyDown(keyCode, event);
		}
		return true;
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.btn_login:
			if(et_pwd.getText().toString().equals("")){
				Toast.makeText(LoginActivity.this,"登录密码不能为空", 0).show();
				return;
			}
			
			btn_login.setBackgroundResource(R.drawable.btn_unclick);
			btn_login.setText("登录中...");
			btn_login.setEnabled(false);
			initData();
			
			break;
		case R.id.message_login:
			Intent intent=new Intent(LoginActivity.this,Message_Login.class);
			intent.putExtra("user_phone", getIntent().getStringExtra("phone"));
			startActivity(intent);
			break;
		case R.id.forget_pwd:
			Intent intent2=new Intent(LoginActivity.this,ForgetPwd.class);
			startActivity(intent2);
			break;
		case R.id.img_back:
			if(who==3){
				LoginActivity.this.finish();
			}else if(who==5){
				
				LoginActivity.this.finish();
				
			}else{
				Intent intent5 = new Intent(LoginActivity.this,MainActivity.class);
				startActivity(intent5);
			}
			break;
		case R.id.switch_account:
			SharedPreferences sharedPreferences=getSharedPreferences("config", MODE_PRIVATE);
			Editor ed=sharedPreferences.edit();
			
			ed.putString("token", "");
			ed.putString("mobile", "");
			ed.putString("usercode", "");
			
			ed.commit();
			Intent intent9=new Intent(LoginActivity.this,Log_or_RegisActivity.class);
			startActivity(intent9);
			LoginActivity.this.finish();
			break;
		case R.id.img_pass:
			if(et_pwd.getTransformationMethod().equals(PasswordTransformationMethod  
                    .getInstance())){
				et_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
				pass.setBackgroundResource(R.drawable.yan1);
			}else{
				et_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
				pass.setBackgroundResource(R.drawable.yan2);
			}
			break;

		case R.id.rl_back:
			if(who==3){
				LoginActivity.this.finish();
			}else if(who==5){
				
				LoginActivity.this.finish();
				
			}else{
				Intent intent5 = new Intent(LoginActivity.this,MainActivity.class);
				startActivity(intent5);
			}
			break;
		case R.id.enterprise_tel:
			BaseHelper.showDialog2(this, "拨号", "400-0101-016", 1);
			break;
		
		}
	}
	
	

}
